package com.naiterui.ehp.bp.support.bean.ser;

import cn.hutool.core.util.NumberUtil;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.naiterui.ehp.bp.support.bean.annotation.FormatOriginalType;

public class FormatOriginalTypeFieldSerializer extends StdSerializer<String> implements ContextualSerializer {

    private FormatOriginalTypeFieldSerializer() {
        super(String.class);
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) {
        FormatOriginalType formatOriginalType = property.getAnnotation(FormatOriginalType.class);
        if (formatOriginalType != null) {
            return new FormatOriginalTypeFieldSerializer();
        }
        return null;
    }

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        if (NumberUtil.isNumber(value)) {
            gen.writeObject(NumberUtil.parseLong(value));
        } else {
            gen.writeObject(value);
        }
    }
}
